<template>
  <div id="userLayout" :class="['user-layout-wrapper']">
    <div class="container">
      <div class="loginbox">
        <div class="top">
          <div class="header">
            <a href="/">
              <img src="/src/assets/images/logo.png" class="logo" alt="BearJia Logo" />
              <span class="title">BearJia Admin</span>
            </a>
          </div>
        </div>
        <div class="main">
          <a-form id="registerForm" ref="registerFormRef" class="user-layout-login" :model="registerFormModel" :rules="registerFormRules" :scrollToFirstError="true">
            <a-page-header title="          用户注册" />
            <a-form-item name="username">
              <a-input v-model:value="registerFormModel.username" size="large" placeholder="用户名">
                <template #prefix>
                  <UserOutlined style="padding-right: 5px; color: blue" />
                </template>
              </a-input>
            </a-form-item>
            <a-form-item name="password">
              <a-input-password v-model:value="registerFormModel.password" size="large" placeholder="密码">
                <template #prefix>
                  <LockOutlined style="padding-right: 5px; color: blue" />
                </template>
              </a-input-password>
            </a-form-item>
            <a-form-item name="confirmPassword">
              <a-input-password v-model:value="registerFormModel.confirmPassword" size="large" placeholder="确认密码">
                <template #prefix>
                  <LockOutlined style="padding-right: 5px; color: blue" />
                </template>
              </a-input-password>
            </a-form-item>
            <a-form-item name="code">
              <a-row :gutter="16">
                <a-col class="gutter-row" :span="16">
                  <a-input v-model:value="registerFormModel.code" size="large" type="text" autocomplete="off" placeholder="验证码">
                    <template #prefix>
                      <SecurityScanOutlined style="padding-right: 5px; color: blue" />
                    </template>
                  </a-input>
                </a-col>
                <a-col class="gutter-row" :span="8">
                  <img class="getCaptcha" :src="registerFormModel.codeUrl" @click="getVerifyCode" />
                </a-col>
              </a-row>
            </a-form-item>
            <a-form-item>
              <a-button size="large" type="primary" htmlType="submit" class="login-button" :disabled="registerFormModel.registerButtonDisabled" :loading="registerFormModel.registerButtonLoading" @click="submitForm()">{{ registerFormModel.registerButtonName }}</a-button>
            </a-form-item>
            <a-form-item>
              <div style="float: left; line-height: 30px">
                已有账号？
                <a-button type="link" @click="goToLogin">立即登录</a-button>
              </div>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { getVerifyCodeImg } from '@/api/login.js';
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { useAppStore } from '@/stores/app';
import { UserOutlined, LockOutlined, SecurityScanOutlined } from '@ant-design/icons-vue';

const vueRouter = useRouter();
const vueStore = useAppStore();

const registerFormRef = ref();

const registerFormModel = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  code: '',
  uuid: '',
  codeUrl: '',
  registerButtonDisabled: false,
  registerButtonLoading: false,
  registerButtonName: '注册',
});

const registerFormRules = reactive({
  username: [
    { required: true, message: '请输入用户名！', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度必须在4-20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码！', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码！', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value === registerFormModel.password) {
          return Promise.resolve();
        }
        return Promise.reject('两次输入的密码不一致！');
      },
      trigger: 'blur'
    }
  ],
  code: [{ required: true, message: '请输入验证码！', trigger: 'blur' }],
});

const getVerifyCode = () => {
  getVerifyCodeImg().then((res) => {
    registerFormModel.codeUrl = 'data:image/gif;base64,' + res.img;
    registerFormModel.uuid = res.uuid;
  });
};

const submitForm = () => {
  registerFormModel.registerButtonDisabled = true;
  registerFormModel.registerButtonLoading = true;
  registerFormModel.registerButtonName = '注册中...';
  registerFormRef.value
    .validate()
    .then(() => {
      // TODO: 调用注册API
      vueStore
        .dispatch('Register_Action', registerFormModel)
        .then(() => {
          vueRouter.push({ path: '/login' });
        })
        .catch(() => {
          registerFormModel.registerButtonDisabled = false;
          registerFormModel.registerButtonLoading = false;
          registerFormModel.registerButtonName = '注册';
          getVerifyCode();
        });
    })
    .catch((error) => {
      registerFormModel.registerButtonDisabled = false;
      registerFormModel.registerButtonLoading = false;
      registerFormModel.registerButtonName = '注册';
      console.log('error', error);
    });
};

const goToLogin = () => {
  vueRouter.push('/login');
};

const resetForm = () => {
  registerFormRef.value.resetFields();
};

getVerifyCode();
</script>

<style lang="less">
@import '@/style/pages/loginPage/loginPageStyles.less';
</style>